package jfc.core;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 *  @author Yann Le Gall
 *  ylegall@gmail.com
 *  Oct 25, 2009 1:14:24 AM
 */
public class Foundation extends CardHolder {

    private LinkedList<Card> stack;
    private int topValue;
    private static final Color COLOR = new Color(0,200,0);

    public Foundation(Point p) {
        super(p);
        topValue = 0;
        stack = new LinkedList<Card>();
    }
    
    public void add(List<Card> list) {
        Card c = list.remove(0);
        c.setLocation(this.getLocation());
        stack.push(c);
        topValue++;
    }

    public boolean canAdd(Card c) {
        if(stack.isEmpty()) {
            return c.getValue() == 1;
        }
        else {
            Card top = stack.peekFirst();
            if(top.isSameSuit(c)) {
                return c.compareTo(top) == 1; }
            else {
                return false; }
        }
    }

    public void add(Card c) {
        if(canAdd(c)){
            c.setLocation(this.getLocation());
            stack.push(c);
            topValue++;
        }
    }

    public void clear() {
        stack.clear();
        topValue = 0;
    }

    public List<Card> remove(int num) {
        if(stack.isEmpty()) return null;
        else {
        	ArrayList<Card> list = new ArrayList<Card>(1);
        	list.add(removeTop());
        	return list;
        }
    }
    
    public Card peekTop() {
    	return stack.peekFirst();
    }
    
    public Card removeTop() {
    	topValue--;
    	return stack.pop();
    }

    public int getTopValue() {
        return topValue;
    }

    public void draw(Graphics2D g2) {
        if (!stack.isEmpty()) {
            stack.getFirst().draw(g2);
        } else {
            Color c = g2.getColor();
            g2.setColor(COLOR);
            g2.fillRoundRect(x, y, width, height, 10, 10);
            g2.setColor(c);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        Iterator<Card> it = stack.descendingIterator();
        while(it.hasNext()) {
            sb.append(it.next().toString());
            sb.append(",");
        }
        return sb.toString();
    }
}
